import 'package:flustars/flustars.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_note/config/router_config.dart';
import 'package:flutter_note/db/db_helper.dart';
import 'package:flutter_note/entity/note.dart';
import 'package:logger/logger.dart';
import 'package:oktoast/oktoast.dart';
import 'package:permission_handler/permission_handler.dart';

class HomePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _HomePageState();
  }
}

class _HomePageState extends State<HomePage> {
  List<Note> notes = [];

  var logger = Logger();

  @override
  void initState() {
    requestPermission().then((bool access) {
      if (access) {
        _getData();
      } else {
        showToast("读取内容失败，未获取读写权限");
      }
    }, onError: (e) => logger.e(e.toString()));
    super.initState();
  }

  void _getData() {
    DbHelper.instance.queryAll().then((value) => _setData(value),
        onError: (e) => logger.e(e.toString()));
  }

  void _delete(int id) {
    DbHelper.instance.delete(id).then((value) {
      logger.d("delete------------>$value");
      if (value > 0) {
        showToast("删除成功!");
        for (int i = 0; i < notes.length; i++) {
          if (notes[i].id == id) {
            logger.d("delete id:$id");
            setState(() {
              notes.removeAt(i);
            });
          }
        }
      }
    });
  }

  void _setData(List<Note> list) {
    logger.d(list.length);

    setState(() {
      notes.clear();
      notes.addAll(list);
      //notes.setAll(0, list);
    });
  }

  void _insertNewNote(Note note) {
    setState(() {
      notes.insert(0, note);
    });
  }

  Future<bool> requestPermission() async {
    /* //请求权限
    Map<PermissionGroup, PermissionStatus> permissions =
        await PermissionHandler().requestPermissions([PermissionGroup.storage]);
    if (permissions[PermissionGroup.storage] == PermissionStatus.granted) {
      return true;
    }*/
    var status = await Permission.storage.request();
    if (status.isGranted) {
      return true;
    }
    return false;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text('记事本'),
      ),
      body: Center(
        child: ListView.separated(
            separatorBuilder: (context, index) => const Divider(
                  height: 2,
                ),
            itemCount: notes == null ? 0 : notes.length,
            itemBuilder: (context, index) => _ItemWidget(
                  notes[index],
                  onDataDelete: () {
                    _delete(notes[index].id);
                  },
                  onDataUpdate: _getData,
                )),
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(
          Icons.add,
        ),
        onPressed: () {
          //Navigator.of(context).pushNamed(routeName)
          Navigator.of(context).pushNamed(RouteName.edit).then((value) {
            //logger.d("result---------->$value");
            if (value is Note) {
              _insertNewNote(value);
            }
          });
        },
      ),
    );
  }
}

class _ItemWidget extends StatelessWidget {
  final Note note;
  final VoidCallback onDataUpdate;
  final VoidCallback onDataDelete;

  _ItemWidget(this.note, {this.onDataUpdate, this.onDataDelete});

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: () {
        Navigator.of(context)
            .pushNamed(RouteName.edit, arguments: note.toMap())
            .then((value) {
          //logger.d("result---------->$value");
          if (value is int && value > 0) {
            onDataUpdate();
          }
        });
      },
      onLongPress: () {
        showModalBottomSheet(
            context: context,
            builder: (context) => Container(
                  height: 60,
                  color: Colors.redAccent,
                  child: InkWell(
                    onTap: () {
                      Navigator.pop(context);
                      onDataDelete();
                    },
                    child: Center(
                      child: Text(
                        '删除',
                        style: TextStyle(color: Colors.white, fontSize: 14),
                      ),
                    ),
                  ),
                ));
      },
      child: Container(
        padding: EdgeInsets.fromLTRB(15, 20, 15, 20),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Text(
              note.content,
              style: TextStyle(fontSize: 14, color: Colors.black54),
            ),
            Text(TimelineUtil.format(note.ts, locale: "zh"),
                style: TextStyle(fontSize: 14, color: Colors.black54)),
          ],
        ),
      ),
    );
  }
}
